﻿using CommonNet48.SerializerUtils;
using DBOptionPro.DAL;
using DBOptionPro.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBOptionPro.BLL
{
    /// <summary>
    /// DBF文件监控同步业务逻辑处理类
    /// </summary>
    public class DBFFileMonitorBLL
    {

        /// <summary>
        /// dbf文件列表保存路径
        /// </summary>
        private string DBFFilesSavePath { get; } = Path.Combine(AppContext.BaseDirectory, "Config", "DBFFileInfo.json");
        private readonly object lockObj = new object();

        public void SaveFiles(List<DBFFileInfo> files)
        {
            try
            {
                lock (lockObj)
                {
                    JsonHelper.ObjectToJsonFile(files, DBFFilesSavePath);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public List<DBFFileInfo> GetFiles()
        {
            try
            {
                return JsonHelper.JsonFileToObject<List<DBFFileInfo>>(this.DBFFilesSavePath);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }

        public int DBFAsync(DBFFileInfo file, SysOption sysOption)
        {
            int count = 0;
            try
            {
                using (MyData_ServerDAL serverDAL = new MyData_ServerDAL(sysOption))
                {
                    using (MyData_DBFDAL dal = new MyData_DBFDAL(file))
                    {
                        var ls = dal.GetDBFDataList();
                        if (ls == null || ls.Count == 0) return 0;
                        foreach (var dbfItem in ls)
                        {
                            count += serverDAL.UpdateDBF(dbfItem);
                        }
                    }
                }
                return count;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return count;
            }
        }
    }
}
